//
//  QueryViewController.m
//  MZJ
//
//  Created by XDD on 16/6/4.
//  Copyright © 2016年 XDD. All rights reserved.
//

#import "QueryViewController.h"
#import "QueryDeatailVC.h"
#import "QueryCell.h"
#import "Type_View.h"
#import "Down_View.h"
#import "MJRefresh.h"
#import "MJRefreshBackStateFooter.h"
#import "MJRefreshStateHeader.h"
#import "XJNetWorkingManager+Request.h"

@interface QueryViewController ()<UITableViewDelegate,UITableViewDataSource,UIScrollViewDelegate> {
    NSInteger page;
    NSString *pandun_All_Str;
}

@property (nonatomic, strong) UITableView *query_TabelView;
@property (nonatomic, strong) UIScrollView *down_ScrollView;
@property (nonatomic, strong) UILabel *downLabel;
@property (nonatomic, strong) NSMutableArray *allarr;
@property (nonatomic, strong) NSArray *arr2;

@property (nonatomic, strong) UILabel *typeLabel;
@property (nonatomic, strong) NetWorkingSModel *model;
@property (nonatomic, strong) ModelViewController *modelViewController;
@property (nonatomic, strong) Down_View *downView;
@property (nonatomic, strong) Type_View *typeView;

@end

@implementation QueryViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
    self.tabBarController.tabBar.hidden = YES;

}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    
    [DataModel object].down_name_Str = nil;
    [DataModel object].down_type_Str = nil;
    [DataModel object].down_ID_Str = nil;
    [DataModel object].type_ID_Str = nil;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [GiFHUD show];

    // Do any additional setup after loading the view.
    self.topBar.backgroundColor = [UIColor colorWithRed:253/255.0 green:179/255.0 blue:10/255.0 alpha:1];
    self.titleLabel.text = @"个案援助";
    self.view.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
    [self.backButton setTitle:@"" forState:UIControlStateNormal];
    
    self.query_TabelView = [[UITableView alloc]initWithFrame:CGRectMake(0, 55+22, kWidth, kHeight - 55-22)];
    self.query_TabelView.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
    self.query_TabelView.delegate = self;
    self.query_TabelView.dataSource = self;
    [self.query_TabelView registerNib:[UINib nibWithNibName:@"QueryCell" bundle:nil] forCellReuseIdentifier:@"queryCell"];
    self.query_TabelView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.query_TabelView];
    
    pandun_All_Str = @"NOALL";
    
    //按镇别
    UIButton *downBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    downBtn.frame = CGRectMake(15, 9 + 55, kWidth/2 - 40, 16);
    downBtn.layer.borderWidth = 1.0;
    downBtn.backgroundColor = [UIColor whiteColor];
    [downBtn addTarget:self action:@selector(downBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:downBtn];
    
    _downLabel = [[UILabel alloc]initWithFrame:CGRectMake(1, 1, kWidth/2 - 50, 14)];
    _downLabel.textAlignment = NSTextAlignmentCenter;
    _downLabel.text = @"按镇别";
    _downLabel.font = [UIFont systemFontOfSize:10];
    [downBtn addSubview:_downLabel];
    
    UIImageView *downImageView = [[UIImageView alloc]initWithFrame:CGRectMake(downBtn.frame.size.width - 11, 3, 8, 10)];
//    downImageView.backgroundColor = [UIColor purpleColor];
    downImageView.image = [UIImage imageNamed:@"arrow_Left_Img"];
    [downBtn addSubview:downImageView];
    
    //按类型
    UIButton *typeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    typeBtn.frame = CGRectMake(15 + 10 + kWidth/2 - 40, 9 + 55, kWidth/2 - 40, 16);
    typeBtn.layer.borderWidth = 1.0;
    typeBtn.backgroundColor = [UIColor whiteColor];
    [typeBtn addTarget:self action:@selector(typeBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view  addSubview:typeBtn];
    
    _typeLabel = [[UILabel alloc]initWithFrame:CGRectMake(1, 1, kWidth/2 - 50, 14)];
    _typeLabel.textAlignment = NSTextAlignmentCenter;
    _typeLabel.text = @"按类别";
    _typeLabel.font = [UIFont systemFontOfSize:10];
    [typeBtn addSubview:_typeLabel];
    
    UIImageView *typeImageView = [[UIImageView alloc]initWithFrame:CGRectMake(typeBtn.frame.size.width - 11, 3, 8, 10)];
//    typeImageView.backgroundColor = [UIColor purpleColor];
    typeImageView.image = [UIImage imageNamed:@"arrow_Left_Img"];
    [typeBtn addSubview:typeImageView];
    
    //搜索按钮
    UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame = CGRectMake(15 + 10 + kWidth/2 - 40 + kWidth/2 - 40 + 15, 9 + 53, 20, 20);
//    searchBtn.layer.borderWidth = 1.0;
    [searchBtn setImage:[UIImage imageNamed:@"search_img@2x"] forState:UIControlStateNormal];
//    searchBtn.backgroundColor = [UIColor redColor];
    [searchBtn addTarget:self action:@selector(searchBtnAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view  addSubview:searchBtn];
    
    page = 1;
    _allarr = [NSMutableArray array];
    //调网络请求接口
    if (!_modelViewController) {
        _modelViewController = [[ModelViewController alloc]init];
        if (!_model) {
            
            _model = [[NetWorkingSModel alloc] init];

            [self requestnetwork];
        }
    }
    
    //下拉刷新
    self.query_TabelView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _allarr = nil;
        if (_allarr == nil) {
            //            _allarr = [NSMutableArray array];
            page = 1;
            [self requestnetwork];
        }
        // 结束刷新
        [self.query_TabelView.mj_header endRefreshing];
        
    }];
    
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    self.query_TabelView.mj_header.automaticallyChangeAlpha = YES;
    
    
    // 上拉刷新
    self.query_TabelView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        page++;
        [self requestnetwork];
//        // 结束刷新
        [self.query_TabelView.mj_footer endRefreshing];
    }];
    
    [XJNetWorkingManager success_DownAndType:^(id responseObject) {
        [DataModel object].down_Name_Arr = responseObject[@"result"][@"town"];
        [DataModel object].type_Name_Arr = responseObject[@"result"][@"type"];

        NSLog(@"%@",[DataModel object].down_Name_Arr);

    } failureHandler:^(NSError *error) {
        
    }];
}


-(void)requestnetwork{
    
    __weak typeof (self)weakSelf = self;
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    
    if ([pandun_All_Str isEqualToString:@"NOALL"]) {
        [dic setObject:@"1" forKey:@"all"];
    }
    [dic setObject:[NSString stringWithFormat:@"%ld",(long)page] forKey:@"page"];
    [_model setBlockWithReturnBlock:^(id returnValue) {
        
        NSLog(@"信息查询 = %@",returnValue);
        weakSelf.arr2 = returnValue[@"result"];
        
        if ( page == 1) {
        weakSelf.allarr = [NSMutableArray array];
        }
        [weakSelf.allarr addObjectsFromArray:weakSelf.arr2];
        
        [weakSelf.query_TabelView reloadData];
        [weakSelf.query_TabelView.mj_footer resetNoMoreData];
    } WithErrorBlock:^(id errorCode) {
        NSLog(@"没有更多数据");
        NSLog(@"%@",errorCode);
        // 结束刷新
        [weakSelf.query_TabelView.mj_footer endRefreshingWithNoMoreData];
    }];
    [weakSelf.model homeAppGetget_message:dic];
    
    [GiFHUD dismiss];

}

- (Down_View *)downView {
    if (!_downView) {
        _downView = [[Down_View alloc]initWithFrame:CGRectMake(0, 55, kWidth, kHeight - 55 - 44)];
        [self.view addSubview:_downView];
        
        __weak typeof (self)weakSelf = self;

        [_downView setDidsingleTapClickActionBlock:^{
            weakSelf.downView.mBview.hidden = YES;
            weakSelf.downView.hidden = YES;
        }];
        
        [_downView setDiddown_Name_ClickActionBlock:^{
            weakSelf.downView.mBview.hidden = YES;
            weakSelf.downView.hidden = YES;
            weakSelf.downLabel.text = [DataModel object].down_name_Str;
//            [weakSelf.query_TabelView reloadData];
        }];
        [_downView setDiddown_ButtonActionBlock:^{
            weakSelf.downView.mBview.hidden = YES;
            weakSelf.downView.hidden = YES;
            weakSelf.downLabel.text = [DataModel object].down_name_Str;
        }];
    }
    return _downView;
}

- (Type_View *)typeView {
    if (!_typeView) {
        _typeView = [[Type_View alloc]initWithFrame:CGRectMake(0, 55, kWidth, kHeight - 55 - 44)];
        [self.view addSubview:_typeView];
        
        __weak typeof (self)weakSelf = self;
        
        [_typeView setDidsingleTapClickActionBlock:^{
            weakSelf.typeView.mBview_type.hidden = YES;
            weakSelf.typeView.hidden = YES;
        }];
        
        [_typeView setDiddown_Name_ClickActionBlock:^{
            weakSelf.typeView.mBview_type.hidden = YES;
            weakSelf.typeView.hidden = YES;
            weakSelf.typeLabel.text = [DataModel object].type_Name_Str;
//            [weakSelf.query_TabelView reloadData];
        }];
        [_typeView setDiddown_ButtonActionBlock:^{
            weakSelf.typeView.mBview_type.hidden = YES;
            weakSelf.typeView.hidden = YES;
            weakSelf.typeLabel.text = [DataModel object].type_Name_Str;

        }];
    }
    return _typeView;
}

//点击返回键
- (void)clickedBackButton:(UIButton *)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
    self.tabBarController.tabBar.hidden = NO;
}

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return _allarr.count;
//    return 11;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 80;
}

//Header的高度
- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section {
//    if (section == 0) {
//        return 1;
//    }
    return 3;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *head = [[UIView alloc]init];
//    if (section == 0) {
//        head.frame = CGRectMake(0, 0, kWidth, 1);
//        head.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
//        
//        return head;
//    }else {
        head.frame = CGRectMake(0, 0, kWidth, 3);
        head.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1];
        
        return head;
//    }
    
//    return 0;
}

//按镇别按钮
- (void)downBtnAction {
    self.downView.hidden = NO;
    _downView.mBview.hidden = NO;
//    [self.downView animationShow];
  
}

//按类别按钮
- (void)typeBtnAction {
    self.typeView.hidden = NO;
    _typeView.mBview_type.hidden = NO;
}

//搜索按钮
- (void)searchBtnAction {
    _allarr = nil;
    pandun_All_Str = @"YESALL";
    if (_allarr == nil) {
        //            _allarr = [NSMutableArray array];
        page = 1;
    }
    
    __weak typeof (self)weakSelf = self;
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    
    if (!IsNilString([DataModel object].type_ID_Str)) {
        [dic setObject:[DataModel object].type_ID_Str forKey:@"tyid"];
        
    }
    if (!IsNilString([DataModel object].down_ID_Str)) {
        [dic setObject:[DataModel object].down_ID_Str forKey:@"tid"];
        
    }
    
        [dic setObject:[NSString stringWithFormat:@"%ld",(long)page] forKey:@"page"];
    [_model setBlockWithReturnBlock:^(id returnValue) {
        
        NSLog(@"信息查询 = %@",returnValue);
        weakSelf.arr2 = returnValue[@"result"];
        
        if ( page == 1) {
            weakSelf.allarr = [NSMutableArray array];
        }
        [weakSelf.allarr addObjectsFromArray:weakSelf.arr2];
        
        [weakSelf.query_TabelView reloadData];
        [weakSelf.query_TabelView.mj_footer resetNoMoreData];
    } WithErrorBlock:^(id errorCode) {
        NSLog(@"没有更多数据");
        NSLog(@"%@",errorCode);
        // 结束刷新
        [weakSelf.query_TabelView.mj_footer endRefreshingWithNoMoreData];
    }];
    [weakSelf.model homeAppGetget_message:dic];
 
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//    NSInteger section = indexPath.section;
    
    static NSString *identifier = @"queryCell";
    QueryCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    //    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    if (!cell) {
        
        cell = [[QueryCell alloc] initWithFrame:CGRectZero];
    }
    cell.nameLabel.text = _allarr[indexPath.section][@"pname"];
    cell.phoneNum_Label.text = [NSString stringWithFormat:@"联系方式 %@",_allarr[indexPath.section][@"pumobile"]];
    cell.masegessLabel.text = _allarr[indexPath.section][@"pdescription"];
    cell.dateLabel.frame = CGRectMake(kWidth - 90, 10, 80, 15);
    cell.dateLabel.textAlignment = NSTextAlignmentRight;
    cell.dateLabel.text = [_modelViewController TimeStamp:_allarr[indexPath.section][@"pstarttime"] form_time:@"yyyy-MM-dd"];
    [cell.headImageView sd_setImageWithURL:[NSURL URLWithString:_allarr[indexPath.section][@"img"]]
                          placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    QueryDeatailVC *queryDeatailVC = [[QueryDeatailVC alloc]init];
    [DataModel object].Query_ID_Str = [NSString stringWithFormat:@"%@",_allarr[indexPath.section][@"pid"]];
    [DataModel object].property_Str = [NSString stringWithFormat:@"%@",_allarr[indexPath.section][@"pname"]];
    [self.navigationController pushViewController:queryDeatailVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
